package com.seqb.manage.reptile.service.impl;

import com.seqb.common.FileType;
import com.seqb.common.ResultVo;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.utils.ReptileUtils;
import com.seqb.manage.choice.dao.ChoiceQuestionDao;
import com.seqb.manage.choice.domain.ChoiceQuestionDO;
import com.seqb.manage.file.dao.FileDao;
import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.reptile.service.PaperReptileService;
import com.seqb.manage.synthesis.dao.SynthesisQuestionDao;
import com.seqb.manage.synthesis.domain.SynthesisQuestionDO;
import com.seqb.utils.FileUtils;
import com.seqb.utils.JsonUtils;
import com.seqb.utils.WatermarkUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/12/9
 */
@Service
public class PaperReptileServiceImpl implements PaperReptileService {
    @Autowired
    private FileDao fileDao;
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Autowired
    private SeqbConfig seqbConfig;
    @Autowired
    private ChoiceQuestionDao choiceQuestionDao;
    @Autowired
    private SynthesisQuestionDao synthesisQuestionDao;

    @Override
    public ResultVo reptile(Map<String, Object> params) {
        try {
            if (null == params || null == params.get("url") || null == params.get("subject")) {
                return ResultVo.error("参数不足！");
            }
            String url = String.valueOf(params.get("url"));
            String subject = String.valueOf(params.get("subject"));
            String type = "1";

            List list = new ArrayList();
            //信息系统项目管理师
            if ("xxxtxmgls".equals(subject)) {
                if (null != params.get("type")) {
                    type = String.valueOf(params.get("type"));
                }
                list = getXxxtxmglsQuestion(url, type);
            }
            return ResultVo.ok().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVo.error("数据解析错误！");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo save(Map<String, Object> params) {
        try {
            if (null == params || null == params.get("url") || null == params.get("subject")) {
                return ResultVo.error("参数不足！");
            }
            String url = String.valueOf(params.get("url"));
            String subject = String.valueOf(params.get("subject"));
            String type = "1";
            //信息系统项目管理师
            if ("xxxtxmgls".equals(subject)) {
                if (null != params.get("type")) {
                    type = String.valueOf(params.get("type"));
                }
                boolean flag = saveXxxtxmglsQuestion(url, type);
                if (!flag) {
                    return ResultVo.error("操作失败！");
                }
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveXxxtxmglsQuestion(String url, String type) {
        try {
            if ("1".equals(type)) {
                //1、选择题
                List list = ReptileUtils.testGetXgwXztQuestion(url);
                List<File> watermarkFile = new ArrayList<>();
                ChoiceQuestionDO choiceQuestion = null;
                for (int i = 0; i < list.size(); i++) {
                    choiceQuestion = new ChoiceQuestionDO();
                    Map itemMap = (Map) list.get(i);
                    String name = (String) itemMap.get("name");
                    type = (String) itemMap.get("type");
                    Long sortNumber = Long.valueOf((String) itemMap.get("sortNumber"));
                    String choiceOption = (String) itemMap.get("choiceOption");
                    String optionType = "1";

                    //当题目有图片链接的时候，下载该图片到服务器，并记录到附件表
                    FileDO file = null;
                    if (null != itemMap.get("img")) {
                        String imgSrc = (String) itemMap.get("img");
                        String fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(imgSrc));
                        String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        boolean flag = FileUtils.downloadFile(imgSrc, filePath);
                        if (flag) {
                            File fileItem = new File(filePath);
                            String oldFileName = imgSrc.substring(imgSrc.lastIndexOf("/") + 1);
                            file = new FileDO(FileType.fileType(oldFileName), fileUrl, oldFileName, null);
                            fileDao.insert(file);
                            choiceQuestion.setFileUrl(fileUrl);
                            //添加到去水印的文件列表
                            watermarkFile.add(fileItem);
                        }
                    }

                    if (null != itemMap.get("optionType")) {
                        optionType = (String) itemMap.get("optionType");
                    }

                    Map optionMap = new HashMap();
                    //1张图片含1个选项(4张)
                    if ("2".equals(optionType)) {
                        Map map = JsonUtils.jsonToMap(choiceOption);
                        String optionUrlA = (String) map.get("A");
                        String optionUrlB = (String) map.get("B");
                        String optionUrlC = (String) map.get("C");
                        String optionUrlD = (String) map.get("D");

                        String fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(optionUrlA));
                        String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        boolean flag = FileUtils.downloadFile(optionUrlA, filePath);
                        if (flag) {
                            watermarkFile.add(new File(filePath));
                        }
                        optionMap.put("A", fileUrl);
                        fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(optionUrlB));
                        fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        flag = FileUtils.downloadFile(optionUrlB, filePath);
                        if (flag) {
                            watermarkFile.add(new File(filePath));
                        }
                        optionMap.put("B", fileUrl);
                        fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(optionUrlC));
                        fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        flag = FileUtils.downloadFile(optionUrlC, filePath);
                        if (flag) {
                            watermarkFile.add(new File(filePath));
                        }
                        optionMap.put("C", fileUrl);
                        fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(optionUrlD));
                        fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        flag = FileUtils.downloadFile(optionUrlD, filePath);
                        if (flag) {
                            watermarkFile.add(new File(filePath));
                        }
                        optionMap.put("D", fileUrl);
                        choiceQuestion.setChoiceOption(JsonUtils.beanToJson(optionMap));
                    }
                    //1张图片含所有选项(1张)
                    else if ("3".equals(optionType)) {
                        Map map = JsonUtils.jsonToMap(choiceOption);
                        String optionUrl = (String) map.get("option");
                        String fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(optionUrl));
                        String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        boolean flag = FileUtils.downloadFile(optionUrl, filePath);
                        if (flag) {
                            watermarkFile.add(new File(filePath));
                        }
                        optionMap.put("option", fileUrl);
                        choiceQuestion.setChoiceOption(JsonUtils.beanToJson(optionMap));
                    } else {
                        choiceQuestion.setChoiceOption(choiceOption);
                    }

                    //保存到选择题表中
                    choiceQuestion.setSubjectId(1L);
                    choiceQuestion.setSubjectName("信息系统项目管理师");
                    choiceQuestion.setName(name);
                    choiceQuestion.setType(type);
                    choiceQuestion.setSortNumber(sortNumber);
                    choiceQuestion.setOptionType(optionType);
                    choiceQuestionDao.insert(choiceQuestion);

                    //更新附件表数据
                    if (null != file) {
                        FileDO update = new FileDO();
                        update.setId(file.getId());
                        update.setDomainField("Attachment");
                        update.setDomainName("ChoiceQuestion");
                        update.setDomainId(choiceQuestion.getId());
                        fileDao.updateById(update);
                    }
                }

                //处理有水印的图片
                WatermarkUtils.convertAllImages(watermarkFile);
            } else if ("2".equals(type)) {
                //2、案例分析
                List<File> watermarkFile = new ArrayList<>();
                for (int i = 0; i < 3; i++) {
                    String content = ReptileUtils.testGetXgwAlfxQuestion(url + "&tno=" + i);
                    Document doc = Jsoup.parse(content);
                    Elements imgs = doc.select("img");
                    FileDO file = null;
                    for (int j = 0; j < imgs.size(); j++) {
                        Element img = imgs.get(j);
                        String src = img.attr("src");
                        String fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(src));
                        String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                        String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                        boolean flag = FileUtils.downloadFile(src, filePath);
                        if (flag) {
                            String oldFileName = src.substring(src.lastIndexOf("/") + 1);
                            file = new FileDO(FileType.fileType(oldFileName), fileUrl, oldFileName, null);
                            fileDao.insert(file);
                            img.attr("src", contextPath + fileUrl);
                            //添加到去水印的文件列表
                            watermarkFile.add(new File(filePath));
                        }
                    }
                    content = doc.select("body").html().toString();
                    SynthesisQuestionDO synthesisQuestion = new SynthesisQuestionDO();
                    //保存到综合题表中
                    synthesisQuestion.setSubjectId(1L);
                    synthesisQuestion.setSubjectName("信息系统项目管理师");
                    synthesisQuestion.setName(content);
                    synthesisQuestion.setType("1");
                    synthesisQuestion.setSortNumber(Long.valueOf(i + 1));
                    synthesisQuestionDao.insert(synthesisQuestion);
                }
                //处理有水印的图片
                WatermarkUtils.convertAllImages(watermarkFile);
            } else if ("3".equals(type)) {
                //3、论文
                List<File> watermarkFile = new ArrayList<>();
                String content = ReptileUtils.testGetXgwLwQuestion(url);
                Document doc = Jsoup.parse(content);
                Elements imgs = doc.select("img");
                FileDO file = null;
                for (int j = 0; j < imgs.size(); j++) {
                    Element img = imgs.get(j);
                    String src = img.attr("src");
                    String fileName = FileUtils.renameSuffix(FileUtils.renameToUuid(src));
                    String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                    String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                    boolean flag = FileUtils.downloadFile(src, filePath);
                    if (flag) {
                        String oldFileName = src.substring(src.lastIndexOf("/") + 1);
                        file = new FileDO(FileType.fileType(oldFileName), fileUrl, oldFileName, null);
                        fileDao.insert(file);
                        img.attr("src", contextPath + fileUrl);
                        //添加到去水印的文件列表
                        watermarkFile.add(new File(filePath));
                    }
                }
                content = doc.select("body").html().toString();
                SynthesisQuestionDO synthesisQuestion = new SynthesisQuestionDO();
                //保存到综合题表中
                synthesisQuestion.setSubjectId(1L);
                synthesisQuestion.setSubjectName("信息系统项目管理师");
                synthesisQuestion.setName(content);
                synthesisQuestion.setType("2");
                synthesisQuestion.setSortNumber(1L);
                synthesisQuestionDao.insert(synthesisQuestion);
                //处理有水印的图片
                WatermarkUtils.convertAllImages(watermarkFile);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return false;
    }

    //获取信息系统项目管理师试题
    private List getXxxtxmglsQuestion(String url, String type) {
        List list = new ArrayList();
        if ("1".equals(type)) {
            list = ReptileUtils.testGetXgwXztQuestion(url);
        } else if ("2".equals(type)) {
            String result = "";
            for (int i = 0; i < 3; i++) {
                result = ReptileUtils.testGetXgwAlfxQuestion(url + "&tno=" + i);
                list.add(result);
            }

        } else if ("3".equals(type)) {
            String result = ReptileUtils.testGetXgwLwQuestion(url);
            list.add(result);
        }
        return list;
    }

}
